<template>
    <div class="app-container">
        <!-- 顶部导航 -->
        <el-header class="header page-title">
            <div class="header-right">
                <div style="display: flex; gap:var(--gap-small); align-items: center;">
                    <SvgIcon size="18px" icon="alert" color="red" />
                    实时告警
                </div>
            </div>
            <div class="header-buttons">
                <el-button type="primary" icon="Refresh" :loading="loading" @click="refreshData"
                    class="tablet-hide-text">
                    <span class="desktop-only">刷新</span>
                </el-button>
                <el-button type="primary" v-permission="['set_exception',
                    'push_exception_email']" icon="Setting" @click="openRulesDialog" class="tablet-hide-text">
                    <span class="desktop-only">报警规则设置</span>
                </el-button>
            </div>
        </el-header>

        <!-- 告警概览 -->
        <div v-loading="loading" element-loading-text="加载中...">
            <Statistics :alarms="alarms"></Statistics>
        </div>

        <!-- 平板端：处理进度和告警分布在上方 -->
        <el-row :gutter="16" class="tablet-top-section">
            <el-col :xs="24" :sm="12" :xl="0">
                <!-- 处理进度 -->
                <el-card class="progress-card tablet-compact tablet-equal-height" v-loading="loading">
                    <template #header>
                        <span>处理进度</span>
                    </template>
                    <AlertProgress :alarms="alarms" />
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :xl="0">
                <!-- 告警分布 -->
                <el-card class="distribution-card tablet-compact tablet-equal-height" v-loading="loading">
                    <template #header>
                        <span>告警分布</span>
                        <el-radio-group v-model="distributionType" size="small" class="tablet-radio-compact">
                            <el-radio-button value="type" label="type">类型</el-radio-button>
                            <el-radio-button value="area" label="area">区域</el-radio-button>
                        </el-radio-group>
                    </template>
                    <AlertDistribution :alarms="unresolvedAlarms" :type="distributionType" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 实时告警和处理状态 -->
        <el-row :gutter="16">
            <!-- 实时告警区域 - 桌面端占16列，平板端占24列 -->
            <el-col :xs="24" :sm="24" :xl="16">
                <el-card body-style="flex: 1;overflow: auto" class="alarm-card" v-loading="loading">
                    <template #header>
                        <div class="header-title">
                            <span>实时告警</span>
                            <el-tag v-if="alarms.length" type="danger" effect="dark" size="small">
                                {{ filteredUnresolvedAlarms.length }}个待处理
                            </el-tag>
                        </div>
                        <div class="header-actions">
                            <!-- 时间快捷筛选 - 平板端隐藏 -->
                            <el-select clearable filterable v-model="timeFilter" placeholder="时间范围" size="small"
                                class="filter-select desktop-only">
                                <el-option label="全部时间" value=""></el-option>
                                <el-option label="今天" value="today"></el-option>
                                <el-option label="昨天" value="yesterday"></el-option>
                                <el-option label="最近三天" value="last3days"></el-option>
                                <el-option label="最近一周" value="lastWeek"></el-option>
                            </el-select>

                            <!-- 位置筛选 -->
                            <el-select clearable filterable v-model="locationFilter" placeholder="位置" size="small"
                                class="filter-select">
                                <el-option label="全部位置" value=""></el-option>
                                <el-option v-for="location in locationOptions" :key="location" :label="location"
                                    :value="location"></el-option>
                            </el-select>

                            <!-- 类型筛选 -->
                            <el-select clearable filterable v-model="alarmTypeFilter" placeholder="类型" size="small"
                                class="filter-select">
                                <el-option label="全部类型" value=""></el-option>
                                <el-option v-for="type in alarmTypes" :key="type" :label="type"
                                    :value="type"></el-option>
                            </el-select>
                        </div>
                    </template>

                    <!-- 告警列表视图 -->
                    <AlertList :alarms="filteredUnresolvedAlarms" @refreshData="fetchData"></AlertList>
                </el-card>
            </el-col>

            <!-- 右侧部分 - 仅在桌面端显示 -->
            <el-col :xs="0" :sm="0" :xl="8" class="desktop-sidebar">
                <!-- 处理进度 -->
                <el-card class="progress-card" v-loading="loading">
                    <template #header>
                        <span>处理进度</span>
                    </template>
                    <AlertProgress :alarms="alarms" />
                </el-card>

                <!-- 告警分布 -->
                <el-card class="distribution-card" v-loading="loading">
                    <template #header>
                        <span>告警分布</span>
                        <el-radio-group v-model="distributionType" size="small">
                            <el-radio-button value="type" label="type">类型</el-radio-button>
                            <el-radio-button value="area" label="area">区域</el-radio-button>
                        </el-radio-group>
                    </template>
                    <AlertDistribution :alarms="unresolvedAlarms" :type="distributionType" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 历史记录部分 -->
        <el-card class="history-card" v-loading="loading">
            <template #header>
                <div class="header-title">
                    <span>历史记录</span>
                    <el-tag v-if="historyTotal" type="info" size="small" class="desktop-only">
                        共 {{ historyTotal }} 条记录
                    </el-tag>
                    <el-tooltip content="历史记录将在7天后自动清除" placement="top" class="desktop-only">
                        <el-tag type="warning" size="small" effect="plain">
                            <i class="el-icon-warning"></i>
                            7天自动清除
                        </el-tag>
                    </el-tooltip>
                </div>
            </template>
            <HistoryAlertList :resolvedAlarms="resolvedAlarms" @refreshData="fetchData"></HistoryAlertList>
        </el-card>
    </div>
    <!-- 添加报警规则设置对话框组件 -->
    <AlarmRulesDialog ref="rulesDialogRef" />
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { handleError } from '@/utils/handleError';
import { useAlarmStore } from '@/stores/alarm';
import AlarmRulesDialog from './components/AlarmRuleDialog.vue'
import Statistics from './components/Statistics.vue';
import AlertList from './components/AlertList.vue';
import HistoryAlertList from './components/HistoryAlertList.vue';
import AlertProgress from './components/AlertProgress.vue';
import AlertDistribution from './components/AlertDistribution.vue';
import SvgIcon from '@/components/icon/SvgIcon.vue';
import { useCompanyStore } from '@/stores/company';
import { useAreaStore } from '@/stores/area';
import { getEventApi } from '@/api/event';
import { getMeterInfoApi } from '@/api/meter';
import { events } from '@/constants'
import dayjs from 'dayjs';
import { getTypeLabel } from '@/utils/device';
// 导入过滤hooks
import useAlarmFilter from './hooks/useAlarmFilter';

const companyStore = useCompanyStore()
const areaStore = useAreaStore()
const alarmStore = useAlarmStore()
const distributionType = ref('type')
const loading = ref(false) // 加载状态

const historyTotal = computed(() => {
    return resolvedAlarms.value.length
})
// 实时告警数据
const alarms = ref([])
const meterList = ref([])

// 按时间排序的函数
const sortByTime = (a, b) => {
    return new Date(b.time) - new Date(a.time)
}

// 按更新时间排序的函数
const sortByUpdateTime = (a, b) => {
    return new Date(b.updated_at) - new Date(a.updated_at)
}

const unresolvedAlarms = computed(() => {
    return alarms.value
        .filter(alarm => alarm.status === 1)
        .sort(sortByTime)
})

const resolvedAlarms = computed(() => {
    return alarms.value
        .filter(alarm => alarm.status === 2 || alarm.status === 3)
        .sort(sortByUpdateTime)
})

// 对话框的引用
const rulesDialogRef = ref(null);

// 打开规则设置对话框
function openRulesDialog() {
    rulesDialogRef.value.openDialog();
}

// 使用筛选hooks
const {
    timeFilter,
    locationFilter,
    alarmTypeFilter,
    alarmTypes,
    locationOptions,
    filterAlarms
} = useAlarmFilter(alarms);
// 筛选后的未解决告警
const filteredUnresolvedAlarms = computed(() => {
    return filterAlarms(unresolvedAlarms.value);
});

function getTitle(item) {
    if (!item) return ''
    let { src_id, event_id, time, value, value_str } = item


    let eventConfig = events.find(event => event.id === event_id)
    let needs = eventConfig?.needs || []
    let params = {
        time: time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '',
        value: value ?? '',
        value_str: value_str
    }

    if (needs.length > 0) {
        if (needs.includes('meter_code')) {
            let meter = meterList.value.find(meter => meter.id === src_id)
            if (!meter) return ''
            let { meter_code, type } = meter
            params = {
                ...params,
                meter_code: meter_code || '',
                type: type ? getTypeLabel(type) : '',
            }
        }

        if (needs.includes('area')) {
            let area = areaStore.getAreaNameById(src_id)
            params = {
                ...params,
                area: area || ''
            }
        }
    }

    if (!eventConfig || !eventConfig.format) return ''

    try {
        return eventConfig.format(params)
    } catch (error) {

        return ''
    }
}

function processAlertData(data) {
    if (!Array.isArray(data)) return []

    return data.map((item) => {
        if (!item) return null
        let { src_id, event_id, time, value, status } = item
        let eventConfig = events.find(event => event.id === event_id)
        let needs = eventConfig?.needs || []
        let location = ''
        if (needs.includes('area')) {
            location = areaStore.getAreaNameById(src_id)
        } else if (needs.includes('meter_code')) {
            let meter = meterList.value.find(meter => meter.id === src_id)
            if (meter) {
                location = meter.installation_location
            }
        }
        return {
            ...item,
            title: getTitle(item),
            time: dayjs(item.time).format('YYYY-MM-DD HH:mm:ss'),
            severityText: item.agent_level === 1 ? '严重' : item.agent_level === 2 ? '警告' : '提示',
            type: eventConfig?.category || '未知类型',
            update_time: item.updated_at ? dayjs(item.updated_at).fromNow() : '',
            location: location || '未知位置',
            area: areaStore.getAreaNameById(src_id),
            status: status || 1 // 确保状态字段存在
        }
    }).filter(Boolean) // 过滤掉null值
}

// 提取数据加载逻辑到一个单独的函数
async function fetchData() {
    loading.value = true // 开始加载
    try {
        // 获取实时告警数据
        let res = await getEventApi({ id: companyStore.currentCompany.id })
        let meterListRes = await getMeterInfoApi({ company_id: companyStore.currentCompany.id })
        meterList.value = meterListRes.data
        alarms.value = processAlertData(res.data)
    } catch (error) {
        handleError(error, '获取告警数据失败')
    } finally {
        loading.value = false // 结束加载
    }
}

// 手动刷新数据的函数
function refreshData() {
    fetchData()
}

// 监听公司变化时刷新数据
watch(() => companyStore.currentCompany, () => {
    fetchData()
}, {
    immediate: true,
})

// 监听未处理告警数量变化
watch(unresolvedAlarms, (newVal) => {
    alarmStore.setUnresolvedCount(newVal.length)
}, { immediate: true })
</script>

<style scoped>
.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.header-right {
    display: flex;
    gap: 16px;
    align-items: center;
}

.alarm-card {
    height: 558px;
    display: flex;
    flex-direction: column;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-actions {
    display: flex;
    gap: 12px;
}

.search-input {
    width: 160px;
}

.distribution-chart {
    height: 300px;
}

.history-detail {
    padding: 16px;
}

.detail-timeline {
    margin-top: 16px;
}

.detail-timeline h4 {
    margin-bottom: 16px;
}

.progress-card,
.distribution-card {
    margin-bottom: 16px;
}

.pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

/* 筛选组件样式 */
.filter-select {
    width: 120px;
    margin-right: 12px;
}

/* 主题色定义 */
.text-primary {
    color: var(--el-color-primary);
}

.text-success {
    color: var(--el-color-success);
}

.text-warning {
    color: var(--el-color-warning);
}

.text-danger {
    color: var(--el-color-danger);
}

.text-info {
    color: var(--el-color-info);
}

/* 平板端特定样式 */
.tablet-top-section {
    margin-bottom: 16px;
}

/* 平板端紧凑卡片样式 */
.tablet-compact {
    margin-bottom: 12px;
}

.tablet-compact .el-card__header {
    padding: 12px 16px;
}

.tablet-compact .el-card__body {
    padding: 12px 16px;
}

/* 平板端单选按钮组紧凑样式 */
.tablet-radio-compact .el-radio-button__inner {
    padding: 4px 8px;
    font-size: 12px;
}

/* 平板端等高卡片 */
.tablet-equal-height {
    height: 280px;
    display: flex;
    flex-direction: column;
}

.tablet-equal-height .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* 图表容器居中 */
.tablet-equal-height .el-card__body>* {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 确保告警分布图表居中 */
.distribution-card.tablet-equal-height .el-card__body {
    padding: 8px;
}

.distribution-card.tablet-equal-height .el-card__body>div {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 处理进度卡片内容居中 */
.progress-card.tablet-equal-height .el-card__body {
    padding: 8px;
    justify-content: center;
}


/* 或者如果你想要更大的边距，可以调整数值 */
@media (max-width: 1919px) {
    .history-card {
        margin-top: var(--gap-normal);
    }
}

/* 中等屏幕优化 */
@media (max-width: 768px) {
    .header-actions {
        gap: 6px;
    }

    .filter-select {
        width: 80px;
        margin-right: 6px;
    }

    .alarm-card {
        min-height: 300px;
    }

    .progress-card,
    .distribution-card {
        margin-bottom: 8px;
    }

    /* 减少卡片内边距 */
    .el-card__header {
        padding: 10px 12px;
    }

    .el-card__body {
        padding: 10px 12px;
    }

    /* 调整等高卡片高度 */
    .tablet-equal-height {
        height: 300px;
    }
}
</style>